//
//  AddBankCardVC.m
//  Zhiche-Carriage
//
//  Created by LeeBruce on 16/7/16.
//  Copyright © 2016年 LeeBruce. All rights reserved.
//

#import "AddBankCardVC.h"
#import "TopBackView.h"
#import "WKProgressHUD.h"
#import "Common.h"
#import "GYBankCardFormatTextField.h"

@interface AddBankCardVC ()<UITextFieldDelegate>

@property (nonatomic,strong) UIScrollView *scrollView;
@property (nonatomic,strong) UITextField *nameTextField;//持卡人
@property (nonatomic,strong) GYBankCardFormatTextField *bankcardTextField;//卡号
@property (nonatomic,strong) UITextField *phoneNumberTextField;//卡类型
@property (nonatomic,strong) UITextField *bankStyleTextField;//手机号
@property (nonatomic,strong)  UIButton *captchaButton;
@property (nonatomic,copy) NSString *cardString;

@property (nonatomic,strong) NSMutableDictionary *postDic;

@property (nonatomic) NSInteger secondCountDown;

@end

@implementation AddBankCardVC

- (void)viewDidLoad {
    [super viewDidLoad];
    self.postDic = [NSMutableDictionary dictionary];
    TopBackView *topBackView= [[TopBackView alloc]initWithFrame:CGRectMake(0, 0, screenWidth, 64) title:@"添加银行卡"];
    
    topBackView.rightButton.hidden = YES;
    [topBackView.leftButton addTarget:self action:@selector(backAction) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:topBackView];
    
    [self initTextField];
    [self initSubViews];
}

- (void)initTextField{
    
    self.nameTextField = [[UITextField alloc]init];
    self.bankcardTextField = [[GYBankCardFormatTextField alloc]init];
    self.bankStyleTextField = [[UITextField alloc]init];
    self.phoneNumberTextField = [[UITextField alloc]init];

    self.nameTextField.delegate = self;
    self.nameTextField.placeholder = @"请输入姓名";

    self.bankcardTextField.delegate = self;
    self.bankcardTextField.placeholder = @"请输入卡号";

    self.bankStyleTextField.delegate = self;
    self.bankStyleTextField.userInteractionEnabled = NO;

//    self.phoneNumberTextField.delegate = self;
//    self.phoneNumberTextField.placeholder = @"请输入银行预留手机号";

    
    self.bankcardTextField.keyboardType = UIKeyboardTypeNamePhonePad;
    self.phoneNumberTextField.keyboardType = UIKeyboardTypeNamePhonePad;

}

- (void)initSubViews{
    
    self.scrollView = [[UIScrollView alloc]initWithFrame:CGRectMake(0, 64, screenWidth, screenHeight)];
    self.scrollView.contentSize = CGSizeMake(screenWidth, screenHeight + 1);
    self.scrollView.backgroundColor = GrayColor;
    self.scrollView.keyboardDismissMode = UIScrollViewKeyboardDismissModeOnDrag;
    [self.view addSubview:self.scrollView];
    UIView *firstV = [[UIView alloc]initWithFrame:CGRectMake(0, 0, screenWidth, cellHeight)];
    firstV.backgroundColor = WhiteColor;
    UILabel *firstL = [[UILabel alloc]initWithFrame:CGRectMake(18, 0, 300, cellHeight)];
    firstL.text = @"请绑定持卡人本人的银行卡";
    firstL.textColor = littleBlackColor;
    firstL.font = Font(14);
    [firstV addSubview:firstL];
    [self.scrollView addSubview:firstV];
    
    UIView *secondV = [self backViewWithFloatY:CGRectGetMaxY(firstV.frame) andString:@"持卡人" andField:self.nameTextField andColor:littleBlackColor];
    
    [self.scrollView addSubview:secondV];
    
    UIView *thirdV = [self backViewWithFloatY:CGRectGetMaxY(secondV.frame) andString:@"卡号" andField:self.bankcardTextField andColor:littleBlackColor];
    
    [self.scrollView addSubview:thirdV];
    
    UIView *fourthV = [self backViewWithFloatY:CGRectGetMaxY(thirdV.frame) andString:@"卡类型" andField:self.bankStyleTextField andColor:littleBlackColor];
    
    [self.scrollView addSubview:fourthV];
    
    //手机号
//    UIView *fifthV = [self backViewWithFloatY:CGRectGetMaxY(fourthV.frame) andString:@"手机号" andField:self.phoneNumberTextField andColor:littleBlackColor];
    
//    [self.scrollView addSubview:fifthV];

    /*
    UIView *sixV = [[UIView alloc]initWithFrame:CGRectMake(0, CGRectGetMaxY(fifthV.frame), screenWidth, cellHeight)];
    sixV.backgroundColor = WhiteColor;
    [self.scrollView addSubview:sixV];
    
    UILabel *label1 = [[UILabel alloc]initWithFrame:CGRectMake(0,0, screenWidth, 0.5)];
    [sixV addSubview:label1];
    label1.backgroundColor = LineGrayColor;
    
    //获取验证吗
    self.captchaButton = [UIButton buttonWithType:UIButtonTypeCustom];
    
    _captchaButton.frame = CGRectMake(screenWidth - 90 * kWidth, (cellHeight - 23)/2.0, 75 * kWidth, 23 * kHeight);
    [_captchaButton setTitle:@"获取验证码" forState:UIControlStateNormal];
    [_captchaButton setTitleColor:YellowColor forState:UIControlStateNormal];
    _captchaButton.backgroundColor = Color_RGB(253, 243, 232, 1);
    [_captchaButton addTarget:self action:@selector(captchaButtonAction:) forControlEvents:UIControlEventTouchUpInside];
    _captchaButton.titleLabel.font = Font(12);
    _captchaButton.layer.cornerRadius = 5;
    _captchaButton.layer.borderColor = YellowColor.CGColor;
    _captchaButton.layer.borderWidth = 0.5;
    
    [sixV addSubview:_captchaButton];
    */
    [self initBottomView];
    
}

- (void)initBottomView{
    /*
    UILabel *messageL = [[UILabel alloc]initWithFrame:CGRectMake(18, 5 * cellHeight + 30, screenWidth - 38, 60)];
    messageL.numberOfLines = 0;
    messageL.textColor = Color_RGB(156, 156, 156, 1);
    messageL.font = Font(11);
    messageL.tag = 200;
    NSString *string = [NSString stringWithFormat:@"%@",self.phoneNumberTextField];
    string = [string stringByReplacingCharactersInRange:NSMakeRange(3, 4) withString:@"****"];
    
//    messageL.text = [NSString stringWithFormat:@"绑定银行卡需要短信确认，验证码已发送至手机%@,请按提示操作",string];
    [self.scrollView addSubview:messageL];
    */
    UIButton *addButton = [UIButton buttonWithType:UIButtonTypeCustom];
    addButton.frame = CGRectMake(18, 5 * cellHeight + 30, screenWidth - 36, Button_height);
    [addButton setTitle:@"添加银行卡" forState:UIControlStateNormal];
    addButton.backgroundColor = YellowColor;
    addButton.layer.cornerRadius = 5;
    [addButton setTitleColor:WhiteColor forState:UIControlStateNormal];
    [addButton addTarget:self action:@selector(addButton) forControlEvents:UIControlEventTouchUpInside];
    [self.scrollView addSubview:addButton];
    
}

- (void)addButton{
    
    [self.postDic setObject:self.pwdString forKey:@"cashPwd"];
    
    if ([[self.postDic allKeys] count] != 3) {
        [WKProgressHUD popMessage:@"请将信息补充完整" inView:self.view duration:1.5 animated:YES];

    } else {
        
 
        [[Common shared] afPostRequestWithUrlString:bind_bankcard parms:self.postDic finishedBlock:^(id responseObj) {
            

            NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:responseObj options:NSJSONReadingMutableLeaves error:nil];
            
            
            [WKProgressHUD popMessage:dic[@"message"] inView:self.view duration:1.5 animated:YES];
            
            if ([dic[@"success"] boolValue]) {
                
                //延迟执行
                dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                    
                    [self.navigationController popViewControllerAnimated:YES];
                    
                });

            }
            
         
        
        } failedBlock:^(NSString *errorMsg) {
            NSLog(@"%@",errorMsg);
        }];
        
    }
    
    
}

- (UIView *)backViewWithFloatY:(CGFloat)y
                     andString:(NSString *)string
                      andField:(UITextField *)field andColor:(UIColor *)color{
    UIView *view = [[UIView alloc]initWithFrame:CGRectMake(0, y, screenWidth, cellHeight)];
    UILabel *label1 = [[UILabel alloc]initWithFrame:CGRectMake(0,0, screenWidth, 0.5)];
    [view addSubview:label1];
    label1.backgroundColor = LineGrayColor;
    
    
    UILabel *titleL = [[UILabel alloc]initWithFrame:CGRectMake(18, 0.5, 100, cellHeight)];
    titleL.text = string;
    titleL.font = Font(13);
    titleL.textColor = fontGrayColor;
    [view addSubview:titleL];
    
    field.frame = CGRectMake(screenWidth - 250 - 18, 1, 250, cellHeight);
    [view addSubview:field];
    view.backgroundColor = WhiteColor;
    field.textAlignment = NSTextAlignmentRight;
    field.textColor = littleBlackColor;
    field.font = Font(13);
    
    return view;
    
    
    //    dispatch_async(dispatch_get_global_queue(0, 0), ^{
    //        // 处理耗时操作的代码块...
    //
    //        //通知主线程刷新
    //        dispatch_async(dispatch_get_main_queue(), ^{
    //            //回调或者说是通知主线程刷新，
    //        });
    //
    //    });

}

- (void)textFieldDidBeginEditing:(UITextField *)textField{
    if (textField == self.bankcardTextField) {
        
        [self.bankcardTextField addTarget:self action:@selector(textFieldDidChange:) forControlEvents:UIControlEventEditingChanged];

    }
    
    if (textField == self.nameTextField) {
        [self.nameTextField addTarget:self action:@selector(nameTextFieldDidChange:) forControlEvents:UIControlEventEditingChanged];
    }

}


- (void)textFieldDidEndEditing:(UITextField *)textField{
    if (textField == self.bankcardTextField) {
        
    }
    
    if (textField == self.nameTextField) {
        
        [self.postDic setObject:self.nameTextField.text forKey:@"userName"];
    }
    
    if (textField == self.phoneNumberTextField) {
//        [self.postDic setObject:self.phoneNumberTextField.text forKey:@"phone"];
    }
    
}

- (void)textFieldDidChange:(UITextField *)textField{
    
    NSString *string = textField.text;
    string = [string stringByReplacingOccurrencesOfString:@" " withString:@""];
    
      self.cardString = string;

    if (string.length >= 16) {
        
        [self checkBankCardWithString:string];
   
    }
} 

- (void)nameTextFieldDidChange:(UITextField *)textfield{
    [self.postDic setObject:self.nameTextField.text forKey:@"userName"];

    
}

- (BOOL)textField:(UITextField *)textField
shouldChangeCharactersInRange:(NSRange)range
replacementString:(NSString *)string{
    
    //姓名防止输入空格
    if (textField == self.nameTextField) {
       
        NSString *tem = [[string componentsSeparatedByCharactersInSet:[NSCharacterSet whitespaceCharacterSet]]componentsJoinedByString:@""];
        if (![string isEqualToString:tem]) {
            return NO;
            
        }
        return YES;
    } else if (textField == self.bankcardTextField) {
        
        NSString * toBeString = [textField.text stringByReplacingCharactersInRange:range withString:string]; //得到输入框的内容
        
        if ([toBeString length] > 23) { //如果输入框内容大于20则弹出警告
            textField.text = [toBeString substringToIndex:23];
            
            [self showAlertController];

            return NO;
        }
        
        return YES;
    } else {
        return YES;
    }
    
  
}


//检测银行卡
- (void)checkBankCardWithString:(NSString *)string{
    
    [[Common shared] afPostRequestWithUrlString:check_bankcard parms:@{@"card":string} finishedBlock:^(id responseObj) {
        
        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:responseObj options:NSJSONReadingMutableLeaves error:nil];
        

        if ([dic[@"success"] boolValue]) {
            self.bankStyleTextField.text = dic[@"data"][@"bankname"];
            
            [self.postDic setObject:string forKey:@"bankCard"];
            
        } else {
            
            
//            [WKProgressHUD popMessage:dic[@"message"] inView:self.view duration:1.5 animated:YES];

        }
        
    } failedBlock:^(NSString *errorMsg) {
        NSLog(@"%@",errorMsg);
    }];
}


- (void)showAlertController{
    
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:nil message:@"银行卡号不能超过20位" preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction *action1 = [UIAlertAction actionWithTitle:@"确认" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        
        
    }];
    
//    UIAlertAction *action2 = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
//        
//    }];
    
    [alert addAction:action1];
//    [alert addAction:action2];
    
    [self presentViewController:alert animated:YES completion:nil];
    
}



//点击return 按钮 去掉
- (BOOL)textFieldShouldReturn:(UITextField *)textField{
    [textField resignFirstResponder];
    return YES;
}


- (void)backAction{
    [self.navigationController popViewControllerAnimated:YES];
}



@end
